<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <!-- 基本信息字段 -->
        <el-col :span="12">
          <el-form-item label="店铺名称" prop="sotreName">
            <el-input v-model="form.sotreName" placeholder="请输入店铺名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺title" prop="storeTitle">
            <el-input v-model="form.storeTitle" placeholder="请输入店铺title" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="店铺电话" prop="storePhone">
            <el-input v-model="form.storePhone" placeholder="请输入店铺电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺地址" prop="storeAddress">
            <el-input v-model="form.storeAddress" placeholder="请输入店铺地址" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="美团店铺" prop="meituanName">
            <el-input v-model="form.meituanName" placeholder="请输入美团店铺" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抖音店铺" prop="douyinName">
            <el-input v-model="form.douyinName" placeholder="请输入抖音店铺" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="红薯店铺" prop="hongshuName">
            <el-input v-model="form.hongshuName" placeholder="请输入红薯店铺" />
          </el-form-item>
        </el-col>

        <!-- 文本域 -->
        <el-col :span="24">
          <el-form-item label="专业技术内容" prop="specificPurposes">
            <el-input v-model="form.specificPurposes" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="服务质量" prop="serviceQuality">
            <el-input v-model="form.serviceQuality" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-col>

        <!-- 图片上传部分 -->
        <el-col :span="12">
          <el-form-item label="首页轮播" prop="swiperIndex">
            <el-upload 
              ref="swiperIndexUpload" 
              :file-list="swiperIndexFileList" 
              :action="uploadUrl" 
              :headers="headers"
              :auto-upload="true" 
              :before-upload="handleBeforeUpload"  
              :on-success="(res, file) => handleUploadSuccess(res, file, 'swiperIndex')"  
              :on-error="handleUploadError" 
              :on-remove="(file, fileList) => handleRemove(file, fileList, 'swiperIndex')" 
              list-type="picture-card"
              accept="image/jpeg,image/png,image/jpg"  
              name="file">
              <i v-if="!uploadLoading.swiperIndex" class="el-icon-plus"></i>
              <el-loading v-else type="spinner" size="small"></el-loading>
              <div slot="tip" class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB，可上传多张</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店内服务轮播" prop="swiperService">
            <el-upload 
              ref="swiperServiceUpload" 
              :file-list="swiperServiceFileList" 
              :action="uploadUrl" 
              :headers="headers"
              :auto-upload="true" 
              :before-upload="handleBeforeUpload"  
              :on-success="(res, file) => handleUploadSuccess(res, file, 'swiperService')"  
              :on-error="handleUploadError" 
              :on-remove="(file, fileList) => handleRemove(file, fileList, 'swiperService')" 
              list-type="picture-card"
              accept="image/jpeg,image/png,image/jpg"  
              name="file">
              <i v-if="!uploadLoading.swiperService" class="el-icon-plus"></i>
              <el-loading v-else type="spinner" size="small"></el-loading>
              <div slot="tip" class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB，可上传多张</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关于我们背景图" prop="aboutusBackground">
            <el-upload 
              ref="aboutusBackgroundUpload" 
              :file-list="aboutusBackgroundFileList" 
              :action="uploadUrl" 
              :headers="headers"
              :auto-upload="true" 
              :before-upload="handleBeforeUpload"  
              :on-success="(res, file) => handleUploadSuccess(res, file, 'aboutusBackground')"  
              :on-error="handleUploadError" 
              :on-remove="(file, fileList) => handleRemove(file, fileList, 'aboutusBackground')" 
              :limit="1"
              list-type="picture-card"
              accept="image/jpeg,image/png,image/jpg"  
              name="file">
              <i v-if="!uploadLoading.aboutusBackground" class="el-icon-plus"></i>
              <el-loading v-else type="spinner" size="small"></el-loading>
              <div slot="tip" class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB，仅可上传1张</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">提 交</el-button>
      <el-button type="primary" @click="refreshCache">刷新缓存</el-button>
    </div>
  </div>
</template>

<script>
import { getSlSysConfig, updateRedisCache, addSlSysConfig, updateSlSysConfig } from "@/api/projects/SlSysConfig";
import { getToken } from "@/utils/auth";

export default {
  name: "SlSysConfig",
  data() {
    return {
      // 上传配置
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传接口地址
      headers: {
        Authorization: "Bearer " + getToken() // 携带token进行身份验证
      },
      uploadLoading: {
        swiperIndex: false,        // 首页轮播上传状态
        swiperService: false,      // 店内服务轮播上传状态
        aboutusBackground: false   // 关于我们背景图上传状态
      },
      
      // 图片文件列表（用于回显）
      swiperIndexFileList: [],        // 首页轮播图列表
      swiperServiceFileList: [],      // 店内服务轮播图列表
      aboutusBackgroundFileList: [],  // 关于我们背景图列表
      
      // 表单参数
      form: {},
      
      // 表单校验
      rules: {
        sotreName: [
          { required: true, message: "店铺名称不能为空", trigger: "blur" }
        ],
        storeTitle: [
          { required: true, message: "店铺title不能为空", trigger: "blur" }
        ],
        storePhone: [
          { required: true, message: "店铺电话不能为空", trigger: "blur" }
        ],
        storeAddress: [
          { required: true, message: "店铺地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 获取配置信息
    this.getConfigInfo();
  },
  methods: {
    /** 获取配置信息并初始化图片列表 */
    getConfigInfo() {
      getSlSysConfig(1).then(response => {
        if (response.data) {
          this.form = response.data;
          // 初始化图片列表
          this.initImageLists();
        }
      }).catch(error => {
        this.$modal.msgError("获取配置信息失败：" + error.message);
      });
    },
    
    /** 初始化图片列表，将接口返回的URL转换为el-upload需要的格式 */
    initImageLists() {
      // 处理首页轮播图
      if (this.form.swiperIndex) {
        this.swiperIndexFileList = this.form.swiperIndex.split(",").map(url => ({
          id: Date.now() + Math.random(),
          name: `swiper_${Date.now()}.jpg`,
          url: url
        }));
      }
      
      // 处理店内服务轮播图
      if (this.form.swiperService) {
        this.swiperServiceFileList = this.form.swiperService.split(",").map(url => ({
          id: Date.now() + Math.random(),
          name: `service_${Date.now()}.jpg`,
          url: url
        }));
      }
      
      // 处理关于我们背景图（单张）
      if (this.form.aboutusBackground) {
        this.aboutusBackgroundFileList = [{
          id: Date.now(),
          name: `about_${Date.now()}.jpg`,
          url: this.form.aboutusBackground
        }];
      }
    },
    
    /** 上传前校验 */
    handleBeforeUpload(file) {
      // 1. 校验文件大小（≤2MB）
      const isLt2MB = file.size / 1024 / 1024 <= 2;
      if (!isLt2MB) {
        this.$message.error(`当前文件 ${file.name} 大小超过 2MB，请压缩后上传`);
        return false;
      }
      
      // 2. 校验文件格式（JPG/PNG）
      const isImg = ["image/jpeg", "image/png", "image/jpg"].includes(file.type);
      if (!isImg) {
        this.$message.error(`当前文件 ${file.name} 格式不支持，请上传 JPG/PNG 图片`);
        return false;
      }
      
      // 3. 开启对应上传区域的加载状态
      // 判断当前上传的是哪个区域的图片
      const uploadRefs = Object.keys(this.$refs).filter(ref => 
        ref.includes('Upload') && this.$refs[ref].uploadFiles.includes(file)
      );
      
      if (uploadRefs.length > 0) {
        const fieldName = uploadRefs[0].replace('Upload', '');
        this.uploadLoading[fieldName] = true;
      }
      
      return true;
    },
    
    /** 上传成功处理 */
    handleUploadSuccess(res, file, field) {
      // 关闭加载状态
      this.uploadLoading[field] = false;
      
      if (res.code === 200) {
        // 根据不同字段处理
        const fileList = this[`${field}FileList`];
        
        // 检查是否重复上传
        const isDuplicate = fileList.some(item => item.url === res.url);
        if (isDuplicate) {
          this.$message.warning(`文件 ${file.name} 已上传，无需重复添加`);
          return;
        }
        
        // 添加到文件列表
        fileList.push({
          id: Date.now() + Math.random(),
          name: file.name,
          url: res.url
        });
        
        // 单张图片特殊处理（如关于我们背景图）
        if (field === 'aboutusBackground' && fileList.length > 1) {
          fileList.shift(); // 移除第一张，只保留最新的
        }
        
        // 更新表单数据（多张图用逗号拼接）
        this.form[field] = fileList.map(item => item.url).join(',');
        this.$message.success(`${this.getFieldName(field)}上传成功`);
      } else {
        this.handleUploadError(res, file);
      }
    },
    
    /** 上传失败处理 */
    handleUploadError(res, file) {
      // 关闭所有上传加载状态
      Object.keys(this.uploadLoading).forEach(key => {
        this.uploadLoading[key] = false;
      });
      
      // 提示错误信息
      this.$message.error(res.msg || `文件 ${file.name} 上传失败，请重试`);
    },
    
    /** 移除图片处理 */
    handleRemove(file, fileList, field) {
      // 更新文件列表
      this[`${field}FileList`] = fileList;
      
      // 更新表单数据
      this.form[field] = fileList.map(item => item.url).join(',');
      
      this.$message.info(`${this.getFieldName(field)}已删除`);
    },
    
    /** 获取字段的中文名称，用于提示信息 */
    getFieldName(field) {
      const fieldMap = {
        swiperIndex: '首页轮播图',
        swiperService: '店内服务轮播图',
        aboutusBackground: '关于我们背景图'
      };
      return fieldMap[field] || field;
    },
    
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateSlSysConfig(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
              } else {
                this.$modal.msgError(response.msg || "修改失败");
              }
            }).catch(error => {
              this.$modal.msgError("修改失败：" + error.message);
            });
          } else {
            addSlSysConfig(this.form).then(response => {
              if (response.code === 200) {
                this.getConfigInfo(); // 重新获取配置信息
                this.$modal.msgSuccess("新增成功");
              } else {
                this.$modal.msgError(response.msg || "新增失败");
              }
            }).catch(error => {
              this.$modal.msgError("新增失败：" + error.message);
            });
          }
        }
      });
    },
    
    /** 刷新缓存 */
    refreshCache() {
      updateRedisCache().then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("刷新成功");
        } else {
          this.$modal.msgError(response.msg || "刷新失败");
        }
      }).catch(error => {
        this.$modal.msgError("刷新失败：" + error.message);
      });
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: center;
  margin-top: 20px;
}
</style>
